package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"strconv"
	"time"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
)

func TrackLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		Log("Info", " [Start Function]: ", c.Request.URL)
		bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
		bodyStr := string(bodyBytes)
		Log("Info", " [PARAMS_POST]: ", bodyStr)
		c.Next()
	}
}

//验证接口签名
func CallBackCheckSign() gin.HandlerFunc {
	return func(c *gin.Context) {
		if err := CallBackCheckSignDo(c); err != nil {
			api.SendResponse(c, err, nil)
			c.Abort()
			return
		}
		c.Next()
	}
}

func CallBackCheckSignDo(c *gin.Context) (err error) {
	t := c.Query("t")
	sign := c.Query("sign")
	tInt64, _ := strconv.ParseInt(t, 10, 64)
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		Log("err", err)
		err := errno.ParamsError
		return err
	}
	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
	//校验签名
	nowTime := time.Now().Unix()
	if nowTime-tInt64 > SignExpire {
		err := errno.SignExpire
		return err
	}
	if tInt64-nowTime > SignExpire {
		err := errno.SignInvalid
		return err
	}
	verify := CreateGateWaySign(t, string(body))
	if verify != sign {
		err := errno.SignError
		return err
	}
	return nil
}
